<template>
  <a-modal
    title="新增采购订单"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="到货时间" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-date-picker
            style="width: 100%"
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到货时间"
            v-decorator="['arrivalTime',{rules: [{ required: true, message: '请选择到货时间！' }]}]"
            @change="arrivalTimeOnChange"/>
        </a-form-item>
        <a-form-item label="订单来源" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-select
            allowClear
            placeholder="请输入订单来源"
            v-decorator="['orderSource',{rules: [{ required: true, message: '请输入订单来源！'}]}]">
            <a-select-option
              v-for="(suppItem,suppIndex) in suppDataList"
              :key="suppIndex"
              :value="suppItem.id">{{ suppItem.suppDataName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <puor-order-table-form-item
          :dataSource="puorDetailList"
          :proList="list.proList"
          :purchaseNum="form.getFieldValue('purchaseNum') ? form.getFieldValue('purchaseNum') : null"
          :unitPrice="form.getFieldValue('unitPrice') ? form.getFieldValue('unitPrice') : null"
          :totalPrice="form.getFieldValue('totalPrice') ? form.getFieldValue('totalPrice') : null"
          @add="
            ({ tableData }) => {
              puorDetailList = tableData
            }
          "
          @del="
            ({ tableData }) => {
              puorDetailList = tableData
            }
          "
        />
        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-textarea
            :rows="3"
            placeholder="请输入备注信息"
            v-decorator="['remarks']"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { puorOrderAdd } from '@/api/modular/main/puororder/puorOrderManage'
import { suppDataList } from '@/api/modular/main/suppdata/suppDataManage'
import { proList } from '@/api/modular/main/pro/proManage'
import puorOrderTableFormItem from '@/views/main/puororder/puorOrderTableFormltem'
import moment from 'moment'
export default {
  components: {
    puorOrderTableFormItem
  },
  data() {
    return {
      puorDetailList: [],
      list: {
        // 产品
        proList: []
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      arrivalTimeDateString: '',
      visible: false,
      confirmLoading: false,
      suppDataList: [],
      form: this.$form.createForm(this),
      ArrivalTime: undefined // 到货时间
    }
  },
  methods: {
    moment,
    // 初始化方法
    async add(record) {
      this.time = new Date().toLocaleDateString()
      this.ArrivalTime = new Date()
      await proList().then(res => {
        this.list.proList = res.data
      })
      this.visible = true
      // 获取订单来源列表
      await suppDataList().then(res => {
          this.suppDataList = res.data
        })
      // 设置初始值
      setTimeout(() => {
        this.form.setFieldsValue({
          orderSource: this.suppDataList.length !== 0 ? this.suppDataList[0].id : ''
        })
      }, 100)
      // 设置初始时间
      this.form.getFieldDecorator('arrivalTime', { initialValue: moment(this.ArrivalTime, 'YYYY-MM-DD HH:mm:ss') })
      this.arrivalTimeDateString = moment(this.ArrivalTime).format('YYYY-MM-DD HH:mm:ss')
      if (!record) {
        return
      }
      if (record.puorDetailList && record.puorDetailList.length > 0) {
        this.puorDetailList = record.puorDetailList.map(item => {
          item.id = undefined
          return item
        })
      }
      setTimeout(() => {
        this.form.setFieldsValue({
          plaNum: record.plaNum,
          orderSource: record.orderSource,
          remarks: record.remarks
        })
      }, 100)
    },
    getCurrentData() {
      return new Date().toLocaleDateString()
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof values[key] === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          // 过滤空值
          if (this.puorDetailList.length === 0) {
            this.confirmLoading = false
            return this.$message.error('产品不能为空')
          }
          // 去除编号空格
          values.code = values.code ? values.code.trim() : values.code
          values.arrivalTime = this.arrivalTimeDateString || null
          values.puorDetailList = this.puorDetailList || null
          puorOrderAdd(values)
            .then(res => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message) // + res.message
              }
            })
            .finally(res => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    arrivalTimeOnChange(date, dateString) {
      this.arrivalTimeDateString = dateString
      this.form.setFieldsValue({
        arrivalTime: moment()
      })
    },
    handleCancel() {
      this.arrivalTimeDateString = ''
      this.form.getFieldDecorator('arrivalTime', { initialValue: null })
      this.form.resetFields()
      this.visible = false
      this.puorDetailList = []
    }
  }
}
</script>
